<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>给简单图案添加纹理-图片合成</title>
    <style>
        canvas{
            border:1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas width="960" height="540"></canvas>

    <script src="/common/lib/gl-renderer.js"></script>

    <script type="module">

        /**
         * 1.创建renderer对象
         * 2.创建webgl程序
         * 3.创建uniform变量
         * 4.将数据存入缓冲区
         * 5.渲染
         * */ 

        //  1.
        const canvas = document.querySelector("canvas");
        const renderer = new GlRenderer(canvas);

        (async function(){
            
            // 2.
            const vertex = `
                attribute vec2 a_vertexPosition;
                attribute vec2 uv;
                varying vec2 vUv;

                void main(){
                    vUv = uv;
                    gl_Position = vec4(a_vertexPosition, 1.0, 1.0);
                }
            `;
            const fragment = `
                #ifdef GL_ES
                    precision mediump float;
                #endif

                uniform sampler2D tMap;
                uniform sampler2D tCat;

                varying vec2 vUv;

                void main(){
                    vec2 st = vUv * 3.0 - vec2(2.0,0.5);

                    vec4 catColor = texture2D(tCat, st);
                    vec4 color = texture2D(tMap, vUv);

                    gl_FragColor.rgb = catColor.rgb;

                    if(catColor.r < 0.4 && catColor.g > 0.5){
                        gl_FragColor.rgb = color.rgb;
                    }

                    gl_FragColor.a = color.a;
                }
            `;
            const program = renderer.compileSync(fragment,vertex);
            renderer.useProgram(program);

            // 3.
            const texture = await renderer.loadTexture("./assets/girl3.jpg");
            const tCat = await renderer.loadTexture("https://static001.geekbang.org/resource/image/20/cc/20febddf9e1edbb9e7bd349e544f24cc.jpg");
            
            renderer.uniforms.tMap = texture;
            renderer.uniforms.tCat = tCat;

            renderer.uniforms.uTime = 0;

            // 4.
            renderer.setMeshData([{
                positions:[
                    [-1, -1],
                    [-1, 1],
                    [1, 1],
                    [1, -1],
                ],
                attributes:{
                    uv:[
                        [0, 0],
                        [0, 1],
                        [1, 1],
                        [1, 0],
                    ]
                },
                cells: [[0, 1, 2], [2, 0, 3]],
            }]);

            // 5.
            renderer.render();

        })();
        
    </script>
</body>
</html>